package pers.mingshan.example;

import java.util.Locale;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JAVA两个线程交替打印1到100
 *
 * @author hanjuntao
 * @date 2025/6/25 0025
 */
public class Print100 {
    private static volatile int count = 0;
    private static final ReentrantLock LOCK = new ReentrantLock();
    private static final Condition CONDITION = LOCK.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                execute();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "奇数线程").start();

        new Thread(() -> {
            try {
                execute();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "偶数线程").start();
    }

    private static void execute() throws InterruptedException {
        String currName = Thread.currentThread().getName();

        while (count < 100) {
            LOCK.lock();

            try {
                while (count % 2 == 0 && !currName.equals("偶数线程")) {
                    CONDITION.await();
                }

                while (count % 2 != 0 && !currName.equals("奇数线程")) {
                    CONDITION.await();
                }

                System.out.println(currName + ":" + count);
                count++;
                CONDITION.signal();
            } finally {
                LOCK.unlock();
            }
        }

    }
}
